<?php

namespace App\Services\ApplyGoldCoinWithdrawSandPay;

use App\Models\User;
use App\Models\Withdraw;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyGoldCoinWithdrawSandPayRequest extends FormRequest
{
	public function rules()
	{
		$user = $this->user();

		if (! $user->cert_number) {
			fail('请先绑定银行卡账号');
		} elseif (! $user->pay_code) {
			fail('请先设置交易密码');
		} elseif ($user->isWithdrawDangerBySandpay()) {
			fail('资金安全指数较低请联系客服确认');
		}

		return [
			'coins' => [
				'required',
				'numeric',
				'min:1',
				$this->coins()
			],
			'pay_code' => $this->paycode(false),

		];
	}

	public function coins()
	{
		return function ($key, $value, $fail) {
			if ($value <= 0) {
				return $fail('请输入正确的提现金额');
			} elseif (! $this->isWithdrawTimeAllowed()) {
				return $fail('银行卡提现需每日'.$this->withdrawTimeAllowedRange().'进行申请，申请后约2小时左右到账。');
			} elseif ($this->user()->gold_coins <= 0) {
				return $fail('可提现余额不足');
			} elseif (! $this->isWithdrawOn()) {
				return $fail('平台尚未开放提现功能');
			} elseif (! $this->user()->isBankBound()) {
				return $fail('提现银行卡未绑定');
			} elseif (! $this->isLowestAmountMatched()) {
				return $fail("提现金额必须大于 '{$this->allowedLowestAmount()}'");
			}  elseif (! $this->isHighestAmountMatched()) {
				return $fail("提现金额必须小于 '{$this->allowedHighestAmount()}'");
			}  elseif (! $this->isGoldCoinsEnough()) {
				return $fail('可提现余额不足');
			}  elseif (! $this->isSandpayMoneyEnough()) {
				return $fail('今日银行卡提现额度已到达平台日限额，请明日再提现');
			}  else {
				return true;
			}
		};
	}

	protected function withdrawTimeAllowedRange()
	{
		return Withdraw::withdrawTimeAllowedRange();
	}

	protected function isWithdrawTimeAllowed()
	{
		return Withdraw::isWithdrawTimeAllowed();
	}

	protected function isWithdrawOn()
	{
		return Withdraw::isWithdrawOn();
	}

	protected function allowedLowestAmount()
	{
		return Withdraw::allowedLowestAmount();
	}

	protected function isLowestAmountMatched()
	{
		return Withdraw::isLowestAmountMatched($this->coins);
	}

	protected function allowedHighestAmount()
	{
		return Withdraw::allowedHighestAmount();
	}

	protected function isHighestAmountMatched()
	{
		return Withdraw::isHighestAmountMatched($this->coins);
	}

	protected function isGoldCoinsEnough()
	{
		return Withdraw::isCoinsEnoughToDeduct($this->user(), $this->coins);
	}

	protected function isSandpayMoneyEnough()
	{
		$actualAmount = Withdraw::willActuallyGetCoinsMinusFreeWithdrawQuota($this->user(), $this->coins)->minus(2);
		$activeFund = Withdraw::allowedSandpayQuota();
		$todaySandyPayWithdrawAmount = Withdraw::todaySandyPayWithdrawAmount();
		return big_decimal($activeFund)->isGreaterThan(big_decimal($todaySandyPayWithdrawAmount)->plus($actualAmount));
	}

}
